﻿var modelURL = getBaseplatformPort();
var xzqField,
    xzqService;
$(document).ready(function () {
    var ordosXAQ = getErdsxqInfo();
    var params = [];
    var cityHtml = "";
    var allStreetsHtml = "";
    for (var i = 0; i < ordosXAQ.length; i++) {
        var xzqdm = ordosXAQ[i].XZQDM;
        var xzqmc = ordosXAQ[i].XZQMC;
        if (xzqdm.length == "4") {
            cityHtml += "<span class='position' xzq_id = " + xzqdm + " style = 'font-size: 16px;font-weight: bold;color: #00000094;'>" + xzqmc + "</span>&nbsp"
        } else if (xzqdm.length == "6") {
            params.push({
                XZQMC: xzqmc,
                XZQDM: xzqdm,
                children: []
            })
            cityHtml += "<span class='position' xzq_id = " + xzqdm + " style = 'font-size: 16px;font-weight: bold;color: #00000094;'>" + xzqmc + "</span>&nbsp"
        } else {
            //从后台获取到的行政区数据已经排好序，所以从前端可以直接判断即可
            for (var j = 0; j < params.length; j++) {
                if (xzqdm.indexOf(params[j].XZQDM) == 0) {
                    params[j].children.push({
                        XZQMC: xzqmc,
                        XZQDM: xzqdm
                    })
                }
            }
        }
    }
    $('#city').html(cityHtml);
    for (var k = 0; k < params.length; k++) {
        var cityMC = params[k].XZQMC;
        var cityDM = params[k].XZQDM;
        var streetHtml = "";
        for (var key in params[k].children) {
            var childMC = params[k].children[key].XZQMC;
            var childDM = params[k].children[key].XZQDM;
            streetHtml += "<span class='position' xzq_id = " + childDM + " style = 'font-size: 14px;color: #43A5F5;'>" + childMC + "</span>&nbsp"
        }
        allStreetsHtml += "<div style = 'margin-bottom: 10px;'><span class='position' xzq_id = " + cityDM + " style = 'font-size: 14px;font-weight: bold;color: #000;'>" + cityMC + ":</span>&nbsp" + streetHtml + "</div>"
    }
    $('#street').html(allStreetsHtml);
    $('.position').click(function () {
        RemoveAllLayers();
        var XZQDM = $(this).attr("xzq_id");
        //根据xzqdm查询范围，获取到范围，定位到该位置
        var extent = getXZQExtents(XZQDM);
        addXZQFeatures(extent);

    });

    $(".navigationToolPan").click(function(evt){
        $(".navigationToolPan").removeClass("navigationToolPanActive");
        $(evt.target).addClass("navigationToolPanActive");
        $(".navigationToolContent").removeClass("navigationToolContentActive");
        $("." + $(evt.target).attr("targetid")).addClass("navigationToolContentActive");
    });
    $(".navigationSearchBtn").click(function(evt){
        var ipt = $(".navigationSearchIpt").val();
        if(ipt){
            searchPoi(ipt,1,10);
        }else{
            showMsgLayer("请输入查询名称");
        }
    });
})

/**
 * 获取兴趣点
 * @param name
 */
function searchPoi(name,page,pageSize,pageHandle){
    var poiData = [];
    $.ajax({
        type: "post",
        async: false,
        crossDomain : true,
        xhrFields : {
            withCredentials: true
        },
        url: modelURL + "map/getTaste",
        data: {
            name: name,
            page: page,
            pageSize: pageSize
        },
        datatype: "json",
        success: function (result) {
            poiData = JSON.parse(result).data;
        },
        error: function (err) {
            showMsgLayer("查询条件错误");
        }
    });
    //TODO 组织poi数据进行展示
    if(poiData && poiData.length > 0){
        var searchHtml = "";
        for(var i = 0 ; i < poiData.length ; i++){
            searchHtml += "<div X='" + poiData[i].X + "' Y='" + poiData[i].Y + "' class='searchItem'>" + poiData[i].NAME + "</div>";
        }
        $(".navigationSearchPan").html(searchHtml);
        $(".searchItem").unbind("click");
        $(".searchItem").click(function(evt){
            $(".searchItem").removeClass("searchItemActive");
            $(evt.target).addClass("searchItemActive");
            RemoveAllLayers();
            var x = parseFloat($(evt.target).attr("X"));
            var y = parseFloat($(evt.target).attr("Y"));
            var name = $(evt.target).html();

            var cartesian3 = Cesium.Cartesian3.fromDegrees(x,y,0)
            var pinBuilder = new Cesium.PinBuilder();
            var plotentity = viewer.entities.add({
                position: cartesian3,
                billboard: {
                   image: pinBuilder.fromText(name, Cesium.Color.BLUE.withAlpha(0.75), 48).toDataURL(),
                   distanceDisplayCondition: 2000,
                   verticalOrigin: Cesium.VerticalOrigin.BOTTOM
                },
                point : {
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    pixelSize: 5,
                    color: Cesium.Color.RED.withAlpha(1)
                }
            });
            MapStatic.flyTo({ lon: x, lat: y, height: 2000 });
        });
        if(!pageHandle){
            layui.use(['laypage'], function() {
                var laypage = layui.laypage;
                laypage.render({
                    elem: 'navigationSearchPage',
                    count: poiData[0].NUM,
                    limit: 10,
                    theme: '#1E9FFF',
                    groups: 1,
                    jump: function(obj, first){
                        if(!first){
                            searchPoi($(".navigationSearchIpt").val().replaceAll(" ",""),obj.curr,obj.limit,true)
                        }
                    }
                    // first: '首页',
                    // last: '尾页',
                    // prev: '<em>←</em>',
                    // next: '<em>→</em>'
                });
            });
        }
    }else{
        $("#navigationSearchPage").html("");
        $(".navigationSearchPan").html("搜索结果为空");
    }
}

//获取所有行政区数据
function getErdsxqInfo() {
    var thisResult = null;
    $.ajax({
        type: "post",
        async: false,
        crossDomain : true,
        xhrFields : {
            withCredentials: true
        },
        url: modelURL + "tree/getErdsxqInfo",
        data: {},
        datatype: "json",
        success: function (result) {
            var data = JSON.parse(result);
            xzqField = data.data.xzqField;
            xzqService = data.data.xzqService;
            thisResult = data.data.data;
        },
        error: function (err) {
            layer.msg("获取数据失败", { icon: 5 });
        }
    });
    return thisResult;
}
//根据行政区代码XZQDM在服务中查询服务范围
function getXZQExtents(XZQDM) {
    var thisResult = null;
    var ip =xzqService+ "/0/query";
    var sql = xzqField + "='" + XZQDM +"'"
    $.ajax({
        type: "get",
        async: false,
        url: ip,
        data: {
            f: "json",
            where: sql
        },
        datatype: "json",
        success: function (result) {
            result = handle2Geojson(result, "arcgis");
            thisResult = result.features;
        },
        error: function (err) { }
    });
    return thisResult;
}

//根据行政区代码查询矢量范围高亮并返回要素信息
function globleGetXZQFeature(XZQDM) {
    var thisResult = null;
    var ip =xzqService+ "/0/query";
    var sql = xzqField + "='" + XZQDM +"'"
    $.ajax({
        type: "get",
        async: false,
        url: ip,
        data: {
            f: "json",
            where: sql
        },
        datatype: "json",
        success: function (result) {
            thisResult = result;
            // result = handle2Geojson(result, "arcgis");
            // addXZQFeatures(result.features);
        },
        error: function (err) { }
    });
    return thisResult;
}

//添加行政区图层并进行定位
function addXZQFeatures(features) {
    var entity = null;
    for (var m = 0; m < features.length; m++) {
        var geom = features[m].geometry;
        var geomtype = geom.type.toLowerCase();
        if (geomtype.indexOf("polygon") > -1) {
            var points = [];
            for (var i = 0; i < geom.coordinates[0][0].length; i++) {
                var lon = geom.coordinates[0][0][i][0];
                var lat = geom.coordinates[0][0][i][1];
                var zuobiao = degreesFromWebMercatorProjection([lon, lat])
                points.push(zuobiao.longitude);
                points.push(zuobiao.latitude);
            }
            entity = viewer.entities.add({
                //polygon: {
                //    hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
                //    material: Cesium.Color.RED.withAlpha(0.5)
                //},
                polyline: {
                    clampToGround: true,
                    material: Cesium.Color.fromCssColorString("#DF73FF"),
                    positions: Cesium.Cartesian3.fromDegreesArray(points),
                    width: 5
                }
            });
        }
    }
    if (entity) {
        viewer.flyTo(entity, {
            offset: {
                heading: Cesium.Math.toRadians(0.0),
                pitch: Cesium.Math.toRadians(-90),
                range: 0
            }
        });
    }
}
//将行政区要素格式转换为geoJSON格式
function handle2Geojson(data, type) {
    var geojson = {
        "type": "FeatureCollection",
        "features": []
    };
    type = type ? type : "arcgis";
    switch (type) {
        case "arcgis":
            var param = data;
            var arcgis = {
                displayFieldName: "",
                fieldAliases: {},
                fields: [],
                features: [param],
                geometryType: param.geometryType,
                spatialReference: param.spatialReference
            }
            if (param.geometryType == "esriGeometryPolygon" || param.geometry.rings) {
                geojson.features.push({
                    "type": "Feature",
                    "geometry": {
                        "type": "Polygon",
                        //"coordinates": [param.geometry.rings]
                        "coordinates": [param.features[0].geometry.rings]
                    },
                    "properties": param.features[0].attributes,
                    "arcgis": arcgis
                });
            }
            break;
        default:
            break;
    }
    return geojson;
}
//将墨卡托投影坐标转换为经纬度坐标
function degreesFromWebMercatorProjection(cartesian) {
    var webMercatorProjection = new Cesium.WebMercatorProjection();
    var cartographic = new Cesium.Cartographic();
    var param = new Cesium.Cartesian3(cartesian[0], cartesian[1])
    cartographic = webMercatorProjection.unproject(param)
    cartographic.longitude = Cesium.Math.toDegrees(cartographic.longitude);
    cartographic.latitude = Cesium.Math.toDegrees(cartographic.latitude);
    return cartographic;
}
